package com.biomatch.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.biomatch.domain.Position;
import com.biomatch.domain.Rule;
import com.biomatch.dto.Pagination;
import com.biomatch.mapper.RuleMapper;
import com.biomatch.service.RuleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.Date;
import java.util.List;

@Service
public class RuleServiceImpl implements RuleService {
    @Autowired
    RuleMapper ruleMapper;

    @Override
    public Rule saveOrUpdateRule(Rule rule) {
       if(StringUtils.isEmpty(rule.getId()))
       {
           QueryWrapper<Rule> ruleQueryWrapper = new QueryWrapper<>();
           ruleQueryWrapper.eq("Name",rule.getName());
           if(ruleMapper.selectCount(ruleQueryWrapper)>0)
           {
               return  null;
           }
           else
           {
               String code = String.valueOf(new Date().getTime());
               rule.setRuleId("R"+ code.substring(5, code.length()));
               rule.setCreateTime(new Date());
               ruleMapper.insert(rule);
               return rule;
           }
       }
       else
       {
           QueryWrapper<Rule> ruleQueryWrapper = new QueryWrapper<>();
           ruleQueryWrapper.eq("Name",rule.getName()).ne("ruleid",rule.getRuleId());
           if(ruleMapper.selectCount(ruleQueryWrapper)>0)
           {
               return  null;
           }
           else
           {
               ruleMapper.updateById(rule);
               return rule;
           }
       }
    }

    @Override
    public IPage<Rule> get4Page(Pagination pagination) {
        Page<Rule> page = new Page<>(pagination.getCurrent(), pagination.getPageSize());
        return ruleMapper.selectPage(page, null);
    }

    @Override
    public List<Rule> getAll() {
        return ruleMapper.selectList(null);
    }

    @Override
    public Rule deleteRule(Rule rule) {
        QueryWrapper<Rule> ruleQueryWrapper = new QueryWrapper<>();
        ruleQueryWrapper.eq("ruleId",rule.getRuleId());
        if(ruleMapper.selectCount(ruleQueryWrapper)>0)
        {
            ruleMapper.deleteById(rule.getId());
            return  rule;
        }
        else
        {
            return  null;
        }
    }
}
